<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-tree :data="treeList" :props="defaultProps" ref="tree" node-key="id" highlight-current
            @node-click="handleNodeClick">
            <div slot-scope="{ node, data }" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border">
          <div class="header-title">
            <span>第</span>
            <el-select class="cd-ml8 cd-mr8" v-model="queryParams.qsId" placeholder="" size="mini" style="width: 60px;"
              @change="qsChange">
              <el-option v-for="item in qsOptions" :key="item.qsId" :label="item.settleIndex"
                :value="item.qsId"></el-option>
            </el-select>
            <span>期计量列表</span>
          </div>
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px"
            @submit.native.prevent>
            <el-form-item label="站点名称" prop="zdName">
              <el-input v-model="queryParams.zdName" placeholder="请输入站点名称" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            </el-form-item>
            <el-row :gutter="10" class="mb8 top-right-btn small-line-height">
              <el-col :span="1.5"
                v-if="dataList && dataList.length > 0 && canOperation() && queryParams.bdId && queryParams.qsId">
                <el-button type="danger" plain size="mini" @click="onDel" v-hasPermi="['cm:bsSettle:edit']"
                  :disabled="multiple">删除</el-button>
                <el-button v-if="canUpdate" type="primary" plain size="mini" @click="doUpdate"
                  v-hasPermi="['cm:bsSettle:edit']">保存</el-button>
                <el-button v-else type="primary" plain size="mini" @click="onUpdate"
                  v-hasPermi="['cm:bsSettle:edit']">编辑</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-if="canOperation() && queryParams.bdId && queryParams.qsId" type="primary" plain
                  size="mini" @click="onAdd" v-hasPermi="['cm:bsSettle:edit']">设定期数</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="primary" plain size="mini" @click="onUploadFile()">附件管理</el-button>
              </el-col>
              <!--              <el-col :span="1.5" v-if="canOperation()">-->
              <!--                <el-button type="primary" size="mini" plain @click="onExamine">发起审批</el-button>-->
              <!--              </el-col>-->
              <!-- <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                  v-hasPermi="['base:bsZd:export']">导出</el-button>
              </el-col> -->
            </el-row>
          </el-form>
          <el-table border stripe v-loading="loading" :data="dataList" :summary-method="getSummaries" show-summary
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="站点名称" align="center" prop="name" min-width="150px" show-overflow-tooltip />
            <el-table-column label="备案合同金额" align="center" prop="htje" min-width="100px" />
            <el-table-column label="实际合同金额" align="center" prop="sjhtje" min-width="100px" />
            <el-table-column label="开工预付款金额" align="center" prop="kgyfkjr" min-width="100px">
              <template slot-scope="scope">
                <el-input-number v-if="canUpdate" size="mini" v-model="scope.row.kgyfkjr" placeholder="" :precision="2"
                  :controls="false" style="width: 100%;"></el-input-number>
                <span v-else>{{ scope.row.kgyfkjr }}</span>
              </template>
            </el-table-column>
            <el-table-column label="占比（%）" align="center" prop="zb" min-width="100px">
              <template slot-scope="scope">
                <el-input-number v-if="canUpdate" size="mini" v-model="scope.row.zb" placeholder="" :precision="2"
                  :controls="false" style="width: 100%;" @change="computeKgyfkjr(scope.row)"></el-input-number>
                <span v-else>{{ scope.row.zb }}</span>
              </template>
            </el-table-column>
            <el-table-column label="扣除奖励基金" align="center" prop="kcjljj" min-width="100px">
              <template slot-scope="scope">
                <el-input-number v-if="canUpdate" size="mini" v-model="scope.row.kcjljj" placeholder="" :precision="2"
                  :controls="false" style="width: 100%;"></el-input-number>
                <span v-else>{{ scope.row.kcjljj }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <examine-and-approve ref="examineAndApproveRef" @callBack="handleQuery" />
    <file-upload-view ref="fileUploadViewRef" :moduleKey="'reportForm'" :disabled="!canOperation()" />
    <zd-select ref="zdSelectRef" :bdId="queryParams.bdId" :qsId="queryParams.qsId" :qsOptions="qsOptions"
      @callBack="handleQuery"></zd-select>
  </div>
</template>

<script>
import { listDataBsStartAdvance, saveBatch, removeQsBsStartAdvance } from "@/api/cm/bsStartAdvance";
import { queryBdSelect } from "@/api/base/bsBd";
import { listBsQs } from "@/api/cm/bsQs";
import { queryReportStatus } from "@/api/cm/reportForm";
import { mapGetters } from "vuex";
import decimal from "@/utils/big-decimal";
import ExamineAndApprove from './examine-and-approve.vue';
import FileUploadView from '@/components/FileUpload/FileUploadView.vue';
import ZdSelect from './zd-select.vue';

export default {
  name: "Yfk",
  dicts: ['report_status'],

  components: {
    ExamineAndApprove,
    FileUploadView,
    ZdSelect
  },
  data () {
    return {
      isHide: false,
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "name"
      },
      qsOptions: [],
      canUpdate: false,
      params: {
        qsId: undefined,
        qs: undefined,
      },
      checkabled: false,
      advanceSelection: [],
      isDisabled: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 站点表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bdId: undefined,
        zdName: undefined,
        name: undefined,
        sort: undefined,
        jianscj: undefined,
        jiansrl: undefined,
        danwzj: undefined,
        beiazmc: undefined,
        bdName: undefined
      },
      projectId: undefined,
      // 表单参数
      form: {},
      multipleSelection: [],
      reportStatus: null,
    };
  },
  // 监听顶部全局下拉
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      // 系统顶部选中项目变化
      this.changeProject(newVal);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.getBdList();
    },
    getBdList () {
      queryBdSelect({ projectId: this.projectId }).then((response) => {
        this.treeList = response.data;
        // 选中左侧树
        this.$nextTick(() => {
          if (this.treeList.length > 0 && this.$refs.tree) {
            this.$refs.tree.setCurrentKey(this.treeList[0].id);
            this.handleNodeClick(this.treeList[0]);
          }
        });
      });
    },
    handleNodeClick (data) {
      this.queryParams.bdId = data.id;
      this.treeInfo = data;
      this.getQs();
      // this.handleQuery();
    },
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 获取期数
    getQs () {
      const queryParams = {
        bdId: this.queryParams.bdId,
        pageNum: 1,
        pageSize: 100,
      };
      listBsQs(queryParams).then(response => {
        this.qsOptions = response.rows;
        if (this.qsOptions.length > 0) {
          // 默认期数
          let qsInfo = this.qsOptions.find(item => item.currentFlag == 1);
          if (!qsInfo) {
            qsInfo = this.qsOptions[this.qsOptions.length - 1];
          }
          this.queryParams.qsId = qsInfo.qsId;
          this.queryParams.qs = qsInfo.qs;
          this.qsChange();
        } else {
          this.queryParams.qsId = null;
          this.queryParams.qs = null;
          this.reportStatus = '';
          this.total = 0;
          this.dataList = [];
        }
      });
    },
    qsChange () {
      const info = this.qsOptions.find(item => item.qsId == this.queryParams.qsId);
      this.queryParams.qs = info.settleIndex;
      this.handleQuery();
      this.getReportStatus();
    },
    // 获取报表状态 00 未审核 33 已驳回  这两个状态时可编辑
    getReportStatus () {
      const query = {
        bdId: this.queryParams.bdId,
        qsId: this.queryParams.qsId
      };
      queryReportStatus(query).then(res => {
        const { status } = res.data;
        this.reportStatus = status;
      });
    },
    /** 查询站点列表 */
    getList () {
      this.loading = true;
      listDataBsStartAdvance(this.queryParams).then((response) => {
        this.dataList = response.data;
        this.loading = false;
      });
    },
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        if (index === 2 || index === 3 || index === 5) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return decimal.add(prev, curr);
              } else {
                return decimal.round(prev);
              }
            }, 0);
            sums[index] += "";
          } else {
            sums[index] = "";
          }
        }
      });

      return sums;
    },
    submitForm () {
      if (this.advanceSelection && this.advanceSelection.length != 0 && this.queryParams.qsId) {
        this.advanceSelection.forEach(e => {
          e.qsId = this.queryParams.qsId;
          e.qs = this.queryParams.qs;
        });
        saveBatch(this.advanceSelection).then(res => {
          this.canUpdate = false;
          this.checkabled = false;
          this.$message.success(res.msg);
          this.getList();
        });
      } else {
        this.canUpdate = false;
        this.checkabled = false;
      }

    },
    onAdd () {
      // const value = this.dataList.map(e => e.id);
      this.$refs.zdSelectRef.init();
    },
    onUpdate () {
      this.canUpdate = true;
    },
    computeKgyfkjr (row) {

      row.kgyfkjr = decimal.divide(decimal.multiply(row.htje, row.zb), 100);
      return row;
    },
    doUpdate () {
      const arr = this.dataList.map(item => {
        let info = item;
        info.qsId = this.queryParams.qsId;
        info.qs = this.queryParams.qs;
        return info;
      });
      saveBatch(arr).then(res => {
        this.canUpdate = false;
        this.checkabled = false;
        this.$message.success('保存成功');
        this.getList();
      });
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    onDel () {
      this.$modal.confirm('是否确认删除选中的数据项？').then(() => {
        this.loading = true;
        const query = {
          qsId: this.queryParams.qsId,
          ids: this.ids
        };
        return removeQsBsStartAdvance(query);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "cm/bsSettle/export",
        {
          ...this.queryParams
        },
        `bsSettle_${new Date().getTime()}.xlsx`
      );
    },

    // 附件上传
    onUploadFile () {
      const info = {
        businessId: this.queryParams.bdId,
        subBusinessId: this.queryParams.qsId,
      };
      this.$refs.fileUploadViewRef.init(info);
    },
    /** 发起审批 */
    async onExamine () {
      try {
        let data = JSON.stringify(this.dataList);
        await saveBatch(data);
        const projectInfo = this.sysProjectList.find(item => item.projectId == this.projectId);
        const info = {
          projectId: this.projectId,
          projectName: projectInfo.projectName,
          bdId: this.queryParams.bdId,
        };
        this.$refs.examineAndApproveRef.init(info);
      } catch (error) {
      }
    },

    // 是否可操作
    canOperation () {
      return this.reportStatus == '00' || this.reportStatus == '33';
    },
    // 状态字典翻译
    reportStatusFormat () {
      return this.selectDictLabel(this.dict.type.report_status, this.reportStatus);
    },
  }
};
</script>
<style lang="scss" scoped>
.boxCenter {
  margin-top: 20px;
  text-align: center;
}

.header-title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px 0;
  font-size: 20px;
  font-weight: 700;
}
</style>
